<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Call\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Call\Logic\MonitorIndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 呼叫数据总览.
 * @Controller
 */
class CallStatistics extends AbstractAction
{
    use ValidateSceneTrait;

    private function typeEnum($data): array
    {
        $timeRange = [
            'start_time' => date('Y-m-d 00:00:00'),
            'end_time' => date('Y-m-d H:i:s'),
        ];
        //今日
        if ($data['type'] == 1) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00'),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //昨日
        if ($data['type'] == 2) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-1 day')),
                'end_time' => date('Y-m-d 00:00:00'),
            ];
        }
        //本月
        if ($data['type'] == 3) {
            $timeRange = [
                'start_time' => date('Y-m-01 00:00:00'),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //上月
        if ($data['type'] == 4) {
            $start = date('Y-m-01 00:00:00', strtotime('-1 month'));
            $timeRange = [
                'start_time' => date('Y-m-01 00:00:00', strtotime('-1 month')),
                'end_time' => date('Y-m-d H:i:s', strtotime('+1 month', strtotime($start))),
            ];
        }
        //本周
        if ($data['type'] == 5) {
            $week = date('w');
            $day = $week ? $week - 1 : 6;
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-' . $day . ' day')),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        if ($data['type'] == 6) {
            $week = date('w');
            $day = $week ? $week - 1 : 6;
            $endTime = date('Y-m-d 00:00:00', strtotime('-' . $day . ' day'));
            $timeRange = [
                'start_time' => date('Y-m-d H:i:s', strtotime('-' . 7 . ' day', strtotime($endTime))),
                'end_time' => $endTime,
            ];
        }
        //默认
        return array_merge($data, $timeRange);
    }

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/call/callStatistics", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 请求参数
        $params = $this->request->inputs(
            ['type'],
        );
        // 校验参数
        $params['type'] = $params['type'] ?? 1;
        $this->validated($params);
        $params['user'] = $user;
        $data = $this->typeEnum($params);
        $query = Db::table('call_record')
            ->where('created_time', '>=', $data['start_time'])
            ->where('created_time', '<', $data['end_time']);
        $total = $query->count();
        //接通数
        $connectTotal = $query->where('call_duration', '>', 0)->count();
        //未接通数
        $notConnectTotal = $query->where('call_duration', '=', 0)->count();
        $rate = $total > 0 ? bcdiv((string)$connectTotal, (string)$total, 6) : 0;
        $rate = $rate > 0 ? bcmul((string)$rate, '100', 2) . '%' : '0.00%';
        return [
            'total' => $total,
            'connectTotal' => $connectTotal,
            'notConnectTotal' => $notConnectTotal,
            'rate' => $rate,
        ];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'in:1,2,3,4,5,6',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.in' => 'type参数值错误',
        ];
    }
}
